// pages/bookDetail/commentInput/commentInput.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    book: {
      type: Object,
      value: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    inputValue: '',
    bottom: 0,
    wordRemain: 500,
    wordTotal: 500
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 输入框和背景消失
    handleDisappear () {
      this.triggerEvent('InputDisappear', {
        isInputting: false
      })
    },
    // 点击输入框
    handleInputFocus (e) {
      this.setData({
        bottom: e.detail.height
      })
    },
    // 输入框失去焦点
    handleInputBlur (e) {
      this.setData({
        bottom: 0
      })
    },
    // 输入时判断字数
    handleInputing (e) {
      this.setData({
        inputValue: e.detail.value,
        wordRemain: this.data.wordTotal - e.detail.value.length
      })
    },
    // 提交评论
    async handleSummit () {
      if (this.data.inputValue === '') {
        wx.showModal({
          title: '提示',
          content: '评论内容不能为空！'
        })
        return
      }
      wx.showLoading({
        title: '评论上传中...'
      })
      const { result } = await wx.cloud.callFunction({
        name: 'addComment',
        data: {
          inputValue: this.data.inputValue,
          bookId: this.data.book.bookId
        }
      })
      if (result.status === 0) {
        wx.showToast({
          title: result.msg,
          icon: 'success'
        })
        this.triggerEvent('InputDisappear', {
          isInputting: false
        })
        this.triggerEvent('UpdateComment', {
          commentId: result.data.commentId,
          content: result.data.content,
          noToast: true
        })
      } else {
        wx.hideLoading()
        wx.showModal({
          title: '警告',
          content: '出现异常！无法添加评论！'
        })
      }
    }
  }
})
